﻿using System.Text.RegularExpressions;
using System.Data;
using System;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Text;
using Saturn.App.FormOper;

namespace Saturn.App.Common
{
    public class ClsCommon
    {
        #region 数字验证
        public static bool IsRegex(string strData)
        {
            string s = "^[0-9]*$";//正则表达式
            Regex reg = new Regex(s);
            if (reg.IsMatch(strData))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 构造单据DT 单据子表
        public static DataTable BillDT()
        {
            DataTable dt = new DataTable();
            //构造好存储扫描数据的DataTable
            dt.Columns.Add("BillCode");  // 单据号
            dt.Columns.Add("UserID");  // 用户ID
            dt.Columns.Add("ScanDate"); // 扫描日期
            dt.Columns.Add("TraceCode"); // 扫描的码
            dt.Columns.Add("TraceType"); // 0：按托盘扫描  1：按箱扫描
            dt.Columns.Add("Type"); // 类别:0：出库扫描、1：回库、2：入库扫描
            dt.Columns.Add("Nums"); //扫描数量：按托盘是1、按箱是手动输入的数量
            return dt;
        }
        #endregion

        #region 生成随机数
        /// <summary>
        /// CreateRandomCode是自定义的函数，参数代表验证码位数
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public static string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(10);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }
        #endregion

        #region CreateDetailTable单据子表
        public static DataTable CreateDetailTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("产品编号", System.Type.GetType("System.String"));
            dt.Columns.Add("产品名称", System.Type.GetType("System.String"));
            dt.Columns.Add("计划", System.Type.GetType("System.String"));
            dt.Columns.Add("实际", System.Type.GetType("System.String"));
            dt.Columns.Add("时间", System.Type.GetType("System.String"));

            dt.Columns.Add("仓库名称", System.Type.GetType("System.String"));
            dt.TableName = "Bill_Detail";
            return dt;
        }
        #endregion

        #region 设置单元格格式
        public static DataGridTextBoxColumn CreateTextBoxStyle(string title, string columnName, int width)
        {
            DataGridTextBoxColumn result = new DataGridTextBoxColumn();
            result.HeaderText = title;
            result.MappingName = columnName;
            result.Width = width;
            return result;
        }
        #endregion

        #region 单据验证

        public static bool IsFinish(string billProgress)
        {
            if (string.IsNullOrEmpty(billProgress))
                return false;
            int i = billProgress.IndexOf("/");
            if (i <= 0)
                return false;
            double realCount = double.Parse(billProgress.Substring(0, i));
            double planCount = double.Parse(billProgress.Substring(i + 1, billProgress.Length - i - 1));
            if (planCount - realCount != 0)
                return false;
            else return true;
        }

        public static bool IsZero(string billProgress)
        {
            if (string.IsNullOrEmpty(billProgress))
                return false;
            int i = billProgress.IndexOf("/");
            if (i <= 0)
                return false;
            double realCount = double.Parse(billProgress.Substring(0, i));
            if (realCount == 0)
                return false;
            else return true;
        }

        public static string GetProductName(BillMainOper billMainDAL, string productCode)
        {
            string value = productCode;
            if (billMainDAL == null) return value;
            foreach (BillDetailOper billDetailDAL in billMainDAL.BillDetail)
            {
                if (string.Equals(billDetailDAL.productCode, productCode))
                    value = billDetailDAL.productName;
            }
            return value;
        }

        public static string ReturnProgress(string realCount, string planCount)
        {
            string value = string.Empty;
            if (string.IsNullOrEmpty(planCount))
                planCount = "0";
            if (string.IsNullOrEmpty(realCount))
                realCount = "0";
            value = realCount + "/" + planCount;
            return value;
        }


        #endregion

        #region 产生GUID
        private static int m_index = 0;
        public static string GetGUID
        {
            get
            {
                m_index++;
                if (m_index > 99999)
                {
                    m_index = 1;
                }
                return DateTime.Now.ToString("yyMMddHHmmss") + m_index.ToString("d5");
            }
        }
        #endregion
    }

    public class XMLHelper
    {
        public static string ConvertDataTableToXML(DataTable xmlDS)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                stream = new MemoryStream();
                writer = new XmlTextWriter(stream, Encoding.Default);
                xmlDS.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                UTF8Encoding utf = new UTF8Encoding();
                return utf.GetString(arr, 0, arr.Length - 1).Trim();
            }
            catch
            {
                return String.Empty;
            }
            finally
            {
                if (writer != null) writer.Close();
            }
        }
        public static DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (Exception ex)
            {
                string strTest = ex.Message;
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }

        public static string ConvertBillXML(DataTable xmlDT)
        {
            // 组装XML
            StringBuilder buffer0 = new StringBuilder();

            //BillCode,Type,UserID,ScanDate,TraceCode,TraceType,Nums,BillType,erpCode
            foreach (DataRow item in xmlDT.Rows)
            {

                buffer0.Append("<BillInfo ");

                // 单据ID
                buffer0.Append("BillID=\"").Append(item["BillID"]).Append("\" ");

                // 单据Code
                buffer0.Append("BillCode=\"").Append(item["BillCode"]).Append("\" ");

                // 单据类型（sap、手工）
                buffer0.Append("Type=\"").Append(item["Type"]).Append("\" ");

                // 用户ID
                buffer0.Append("UserID=\"").Append(item["UserID"]).Append("\" ");

                // 扫描时间
                buffer0.Append("ScanDate=\"").Append(item["ScanDate"]).Append("\" ");

                // 扫描的码
                buffer0.Append("TraceCode=\"").Append(item["TraceCode"]).Append("\" ");

                // 扫描码的类型（箱、垛）
                buffer0.Append("TraceType=\"").Append(item["TraceType"]).Append("\" ");

                // 数量
                buffer0.Append("Nums=\"").Append(item["Nums"]).Append("\" ");

                // 发货、收货、回库
                buffer0.Append("BillType=\"").Append(item["BillType"]).Append("\" ");

                buffer0.Append(">");


                buffer0.Append("</BillInfo>");

            }
            return buffer0.ToString();
        }

        public static string ConvertInventoryXML(DataTable xmlDT)
        {
            // 组装XML
            StringBuilder buffer0 = new StringBuilder();

            //ProductId,Location,PileNum, BoxNum,OrgID,AddUserID,version,AddDate
            foreach (DataRow item in xmlDT.Rows)
            {

                buffer0.Append("<Inventory ");

                // 扫描的码
                buffer0.Append("ProductId=\"").Append(item["ProductId"]).Append("\" ");

                // 货位
                buffer0.Append("Location=\"").Append(item["Location"]).Append("\" ");

                // 多少垛
                buffer0.Append("PileNum=\"").Append(item["PileNum"]).Append("\" ");

                // 多少箱
                buffer0.Append("BoxNum=\"").Append(item["BoxNum"]).Append("\" ");

                // 用书所属机构
                buffer0.Append("OrgID=\"").Append(item["OrgID"]).Append("\" ");

                // 用户
                buffer0.Append("AddUserID=\"").Append(item["AddUserID"]).Append("\" ");

                // 是否分版本
                buffer0.Append("version=\"").Append(item["version"]).Append("\" ");

                // 扫描时间
                buffer0.Append("AddDate=\"").Append(item["AddDate"]).Append("\" ");

                buffer0.Append(">");


                buffer0.Append("</Inventory>");

            }
            return buffer0.ToString();
        }

    }
}